package com.imdroid.carac.process;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;

import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;
import com.imdroid.carac.activities.TeamMapActivity;
import com.imdroid.carac.net.HttpHelper;

public class PlaySoundProcess {

	private static SoundPool pool;
	/**
	 * The sound of the start
	 */
	public static int start;
	/**
	 * The sound of the end
	 */
	public static int end;
	/**
	 * The sound of the wrong
	 */
	public static int wrong;
	/**
	 * The sound of join to team
	 */
	public static int confirm;
	/**
	 * The sound of reject to team
	 */
	public static int reject;
	/**
	 * The sound of exit the team
	 */
	public static int exit;
	/**
	 * The sound of receive the invitation
	 */
	public static int invite;
	/**
	 * The files that waiting to be downloaded
	 */
	private static ArrayList<String> filesWaitingDownload = new ArrayList<String>();
	/**
	 * 
	 */
	private static volatile boolean downloaderWorking = true;

	/**
	 * The pointer to which file currently playing in the last ten list
	 */
	private static volatile int currentListPosition = 0;

	/**
	 * 可重复播放的最后十条语音信息列表
	 */
	private static ArrayList<String> lastTen = new ArrayList<String>();

	/**
	 * 上一个播放最后十条信息里面的播放器
	 */
	private static MediaPlayer lastListPlayer;

	// /**
	// * 最后十个文件中的一个上一次播放的文件指针（文件名）
	// */
	// private static String lastFile;

	/**
	 * 需要播放的文件列表
	 */
	private static LinkedList<String> soundFiles = new LinkedList<String>();

	/**
	 * 上一个播放器
	 */
	private static MediaPlayer lastPlayer;

	/**
	 * 上一个正在播放的刚从网上收到的文件。
	 */
	private static String lastReceivedFile;

	/**
	 * 下载文件线程
	 */
	private static Thread downloadThread;

	/**
	 * Play the sound
	 * 
	 * @param action
	 *            the tag of the sound
	 */
	public static void playSound(int action) {
		if (pool == null) {
			pool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
			start = pool.load(IMDroid.getContext(), R.raw.start, 1);
			end = pool.load(IMDroid.getContext(), R.raw.end, 2);
			wrong = pool.load(IMDroid.getContext(), R.raw.wrong, 3);
			confirm = pool.load(IMDroid.getContext(), R.raw.confirm, 4);
			reject = pool.load(IMDroid.getContext(), R.raw.reject, 5);
			exit = pool.load(IMDroid.getContext(), R.raw.exit, 6);
			invite = pool.load(IMDroid.getContext(), R.raw.invite, 7);
		}

		// 初始化
		if (action == -100)
			return;

		// 连续试播三次，使用成功播放的机会加大
		int res = pool.play(action, 1, 1, 1024, 0, 1);
		if (res == 0) {
			res = pool.play(action, 1, 1, 1024, 0, 1);
		}
		if (res == 0) {
			res = pool.play(action, 1, 1, 1024, 0, 1);
		}
	}

	/**
	 * 查找并播放列表中的下一条信息
	 */
	public static void seekAndPlayNext() {
		// String next = null;
		// if(lastFile == null){
		// if(lastTen.size() > 0) {
		// next = lastTen.get(0);
		// lastFile = next;
		// } else
		// return;
		// }
		// if(next == null){
		// for(int i=0; i < lastTen.size(); i++){
		// if(lastFile.equals(lastTen.get(i))){
		// if(i > 0){
		// next = lastTen.get(i - 1);
		// lastFile = next;
		// } else if(lastListPlayer == null){
		// next = lastTen.get(0);
		// lastFile = next;
		// }
		// break;
		// } else if(i == lastTen.size() - 1){
		// next = lastTen.get(lastTen.size() - 1);
		// lastFile = next;
		// }
		// }
		// }
		// if(next != null)
		// speakList(next);

		String file = null;
		synchronized (lastTen) {
			if (currentListPosition > 0) {
				currentListPosition--;
				file = lastTen.get(currentListPosition);
			}
		}
		if (file != null)
			speakList(file);
	}

	/**
	 * 查找并播放列表中的上一条信息
	 */
	public static void seekAndPlayPrevious() {
		// String previous = null;
		// if(lastFile == null){
		// if(lastTen.size() > 0) {
		// previous = lastTen.get(0);
		// lastFile = previous;
		// } else
		// return;
		// }
		// if(previous == null) {
		// for(int i=0; i < lastTen.size(); i++){
		// if(lastFile.equals(lastTen.get(i))){
		// if(i + 1 < lastTen.size()){
		// previous = lastTen.get(i + 1);
		// lastFile = previous;
		// } else if(lastListPlayer == null){
		// previous = lastTen.get(i);
		// lastFile = previous;
		// }
		// break;
		// } else if(i == lastTen.size() - 1){
		// lastFile = lastTen.get(lastTen.size() - 1);
		// }
		// }
		// }
		// if(previous != null)
		// speakList(previous);

		String file = null;
		synchronized (lastTen) {
			if (currentListPosition < lastTen.size() - 1) {
				currentListPosition++;
				file = lastTen.get(currentListPosition);
			}
		}
		if (file != null)
			speakList(file);
	}

	/**
	 * 播放在列表中的文件（上一条下一条）
	 * 
	 * @param fileInList
	 */
	public static void speakList(String fileInList) {
		if (lastPlayer != null) {
			lastPlayer.pause();
			lastPlayer.seekTo(0);
		}
		if (lastListPlayer != null) {
			lastListPlayer.stop();
			lastListPlayer.release();
			lastListPlayer = null;
		}

		try {
			lastListPlayer = new MediaPlayer();
			final FileInputStream fis = new FileInputStream(IMDroid.TEMP_FOLDER
					+ fileInList);
			lastListPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			lastListPlayer.setDataSource(fis.getFD());
			lastListPlayer.prepare();
			lastListPlayer.start();
			lastListPlayer
					.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
						public void onCompletion(MediaPlayer mp) {
							onMediaPlayerCompletion(mp, fis);
						}
					});
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * Really play the sound.
	 * 
	 * @param soundFile
	 */
	public static void realSpeak(String soundFile) {

		if (TeamMapActivity.instance != null) {
			try {
				int userId = Integer.parseInt(soundFile.substring(0,
						soundFile.indexOf("_")));
				if (userId != 0)
					TeamMapActivity.instance.showMember(userId);
				// 静音
				if (TeamMapActivity.instance.isMute())
					return;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (lastPlayer != null) {
			try {
				lastPlayer.stop();
				lastPlayer.release();
				lastPlayer = null;
			} catch (Exception e) {
			}
		}
		try {
			MediaPlayer mp = new MediaPlayer();
			lastPlayer = mp;
			lastReceivedFile = soundFile;
			final FileInputStream fis = new FileInputStream(IMDroid.TEMP_FOLDER
					+ soundFile);
			mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mp.setDataSource(fis.getFD());
			mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
				public void onCompletion(MediaPlayer mp) {
					onMediaPlayerCompletion(mp, fis);
				}
			});
			mp.prepare();
			mp.start();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * The
	 * 
	 * @param soundFile
	 *            the sound of the file
	 */
	public static void speak(String soundFile) {
		if (downloadThread == null || !downloadThread.isAlive()
				|| !downloaderWorking) {
			downloaderWorking = true;
			downloadThread = new Thread(downloader);
			downloadThread.start();
		}
		synchronized (filesWaitingDownload) {
			filesWaitingDownload.add(soundFile);
			filesWaitingDownload.notifyAll();
		}
	}

	public static void speak2(String soundFile) {
		if (lastListPlayer != null) {
			try {
				lastListPlayer.stop();
				lastListPlayer.release();
				lastListPlayer = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if ((lastPlayer != null && lastPlayer.isPlaying())) {
			soundFiles.add(soundFile);
		} else if (lastPlayer != null) {
			try {
				lastPlayer.start();
			} catch (Exception e) {
				realSpeak(soundFile);
			}
		} else {
			realSpeak(soundFile);
		}
	}

	private static void onMediaPlayerCompletion(MediaPlayer mp,
			FileInputStream fis) {
		mp.stop();
		mp.release();
		try {
			fis.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		PlaySoundProcess.playSound(PlaySoundProcess.end);
		if (mp == lastListPlayer) {
			lastListPlayer = null;
			if (currentListPosition > 0) {
				currentListPosition--;
				String file = null;
				synchronized (lastTen) {
					if (currentListPosition < lastTen.size()) {
						file = lastTen.get(currentListPosition);
					} else {
						currentListPosition = lastTen.size() - 1;
						file = lastTen.get(currentListPosition);
					}
				}
				if (file != null)
					speakList(file);
			} else {
				currentListPosition = -1;
			}
		} else {
			lastPlayer = null;
			currentListPosition = -1;
			if (lastReceivedFile != null) {
				synchronized (lastTen) {
					lastTen.add(0, lastReceivedFile);
					if (lastTen.size() > 10)
						lastTen.remove(lastTen.size() - 1);
				}
			}
			lastReceivedFile = null;
		}
		if (lastPlayer != null) {
			lastPlayer.start();
			return;
		}
		if (soundFiles.size() > 0) {
			realSpeak(soundFiles.removeFirst());
		}
	};

	private static Runnable downloader = new Runnable() {
		public void run() {
			while (downloaderWorking) {
				String soundFile = null;
				synchronized (filesWaitingDownload) {
					while (filesWaitingDownload.size() == 0) {
						try {
							filesWaitingDownload.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					soundFile = filesWaitingDownload.remove(0);
				}
				// 下载文件
				try {
					HttpHelper.download(soundFile);
				} catch (Exception e) {
					e.printStackTrace();
					return;
				}
				speak2(soundFile);
			}
		}
	};

	// /**
	// * 升序比较器
	// */
	// private static Comparator<String> timeComparator = new
	// Comparator<String>() {
	// @Override
	// public int compare(String lhs, String rhs) {
	// lhs = lhs.substring(lhs.indexOf("_") + 1, lhs.lastIndexOf('.'));
	// rhs = rhs.substring(rhs.indexOf("_") + 1, rhs.lastIndexOf('.'));
	// long v1 = Long.parseLong(lhs);
	// long v2 = Long.parseLong(rhs);
	// return v1 > v2 ? 1 : v1 == v2 ? 0 : -1;
	// }
	// };
	//
	// /**
	// * AMR文件过滤器
	// */
	// private static FilenameFilter nameFilter = new FilenameFilter(){
	// @Override
	// public boolean accept(File dir, String filename) {
	// if(filename.endsWith(".amr") && !filename.startsWith("" +
	// IMDroid.getUser().getUser_id())){
	// // 7 * 24 * 60 * 60 * 1000 = 604800000, 老于7天的文件放弃，不再添加到列表
	// long time = Long.parseLong(filename.substring(filename.indexOf("_") + 1,
	// filename.lastIndexOf('.')));
	// if(System.currentTimeMillis() - time > 604800000)
	// return false;
	//
	// return true;
	// }
	// return false;
	// }
	//
	// };

	public static void clearLastTen() {
		synchronized (lastTen) {
			lastTen.clear();
		}
	}

	static {
		playSound(-100);
		// try{
		// File file = new File(IMDroid.TEMP_FOLDER);
		// String[] names = file.list(nameFilter);
		// if(names != null){
		// Arrays.sort(names, timeComparator);
		// for(int i=0; i<10 && i<names.length; i++){
		// lastTen.add(names[names.length - i - 1]);
		// }
		// }
		// } catch(Exception e){
		// e.printStackTrace();
		// }
	}

}
